//设置根路径
axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'

// 获取元素
const tb = document.querySelector('#tb');

// 封装渲染页面函数
function renderBooks() {
  axios.get('/api/getbooks').then(({ data: res }) => {
    // console.log(res);
    const { data } = res
    const html =  data.map((item) => {
      return `
    <tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="#" data-id="${item.id}">删除</a></td>
    </tr>
  `
    }).join('')
    tb.innerHTML = html
  })
  
}
renderBooks()

// 添加表单提交事件
const form = document.querySelector('form');
form.addEventListener('submit', function (e) {
e.preventDefault()
  // 利用serialize方法获取表单name
  const data = serialize(form, { hash: true })
  // console.log(data);
  axios.post('/api/addbook',data).then(({ data: res }) => {
    // console.log(res);
    alert(res.msg)
    if (res.status !== 201) { return }
    renderBooks()
    form.reset()
   })
  
})

// 删除
tb.addEventListener('click', function (e) {
  if (e.target.tagName = 'A') {
    const id = e.target.dataset.id
    // console.log(id);
    axios.get('/api/delbook', { params: { id } }).then(({ data: res }) => { 
      // console.log(res);
      renderBooks()
    })
   }
});

// 查询
const search = document.querySelector('#search');
search.addEventListener('click', function (e) {
    // 阻止默认行为
    e.preventDefault()
    const data = serialize(form, { hash: true })
    // console.log(data);
  axios.get('/api/getbooks', {
    params:data   
  }).then(({ data: res }) => {
    const { data } = res
    tb.innerHTML =  data.map(( item ) => { 
      return `
      <tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="#" data-id="${item.id}">删除</a></td>
    </tr>
      `     
    }).join('')
   })
  });
  
